package services

import (
	"fmt"
    "container/list"
    "github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/gudp"
	"github.com/gogf/gf/os/gtime"
	"time"
)

type UdpService struct {
    name string
    ipList list.List
}

func CreateUdpSer() *UdpService {
    udpSer := new(UdpService)

    // Server
	go gudp.NewServer("0.0.0.0:8999", func(conn *gudp.Conn) {
		defer conn.Close()
		for {
            fmt.Println( "remote addr:",conn.RemoteAddr())
			data, err := conn.Recv(-1)
			if len(data) > 0 {
				if err := conn.Send(append([]byte("> "), data...)); err != nil {
					g.Log().Error(err)
				}
			}
			if err != nil {
				g.Log().Error(err)
			}
		}
	}).Run()

    /*gtime.Add(2000, func (){

    })*/
    for {
        if conn, err := gudp.NewConn("255.255.255.255:8999"); err == nil {
            if err := conn.Send([]byte(gtime.Datetime())); err == nil {
                fmt.Println( "local addr:",conn.LocalAddr())
            } else {
                g.Log().Error(err)
            }
            conn.Close()
        } else {
            g.Log().Error(err)
        }
        time.Sleep(time.Second * 2)
    }

    return udpSer
}

func (udpSer *UdpService) Start()  {
    udpSer.ipList.PushBack("111")
    fmt.Printf("udpser %s %d\n",udpSer.name,udpSer.ipList.Len())
}
